#include "sr.h"

#define READY  1
#define RUNNING  2
#define COUNTING  3

static int state;
static int count;
    
void
initCheckMinMaxPos(void) {
    state = READY;
    count = 0;
}

void
checkMinMaxPosFire(char SWPoscarMin, char SWPoscarMax, int *craneKnownFlags, 
        int *cranePresentFlags) {

    if(state == RUNNING) {
        if(GET_BIT(*craneKnownFlags, SWPOSCARMINBIT) && 
                GET_BIT(*craneKnownFlags, SWPOSCARMAXBIT)) {
            if(GET_BIT(*cranePresentFlags, SWPOSCARMINBIT) && 
                    GET_BIT(*cranePresentFlags, SWPOSCARMAXBIT)) {
                if(SWPoscarMin == 1 || SWPoscarMax == 1) {
                    count++;
                }
                else {
                    count = 0;
                }

                if(count > 10) {
                    SET_BIT_TRUE(*craneKnownFlags, EMSTOPCHECKMINMAXBIT);
                    SET_BIT_TRUE(*cranePresentFlags, EMSTOPCHECKMINMAXBIT);
                    initCheckMinMaxPos();
                }
            }
        }
    }

    if(GET_BIT(*craneKnownFlags, SWPOSCARMINBIT) && 
            GET_BIT(*craneKnownFlags, SWPOSCARMAXBIT) && 
            !GET_BIT(*craneKnownFlags, EMSTOPCHECKMINMAXBIT)) {
        SET_BIT_TRUE(*craneKnownFlags, EMSTOPCHECKMINMAXBIT);
    }
}

void
checkMinMaxPosPostfire(int hasEventFlags, int craneKnownFlags, int cranePresentFlags) {
    switch(state) {
        case READY : {
            if(GET_BIT(craneKnownFlags, TRIGGERBIT)) {
                if(GET_BIT(cranePresentFlags, TRIGGERBIT) && 
                        GET_BIT(hasEventFlags, SHUTDOWNBIT)) {
                    state = RUNNING;
                }
            }
        } break;

        case RUNNING: {
            if(GET_BIT(hasEventFlags, SHUTDOWNBIT)) {
                initCheckMinMaxPos();
                break;
            }
            if(GET_BIT(craneKnownFlags, EMSTOPMERGERBIT)) {
                if(GET_BIT(cranePresentFlags, EMSTOPMERGERBIT)) {
                    initCheckMinMaxPos();
                }
            }
        } break;
    }
}
